<template>
  <div>
    <p>{{ options.uid }}</p>
    <input v-model="options.uid" />
    <el-button @click="join()">join</el-button>
    <el-button @click="leave()">leave</el-button>
    <div class="con">
      <div>
        <h3>对方{{ remoteUsers.id }}</h3>
        <div ref="remotevideoRef" class="remoteVideo"></div>
      </div>
      <div>
        <h3>自己{{ options.uid }}</h3>
        <div ref="localvideoRef" class="localVideo"></div>
      </div>
    </div>
  </div>
</template>

<script>
import AgoraRTC from "agora-rtc-sdk-ng"
export default {
  data() {
    return {
      options: {
        // Pass your App ID here.
        appid: "3d38246f5aee45de8bd8d57a536d94eb",
        // Set the channel name.
        channel: "ch1",
        // Pass your temp token here.
        token: "0063d38246f5aee45de8bd8d57a536d94ebIACAm5cALBb8nFPWLKDI1NFv98PURE6+4oFpHQvobOUBz/5NKkkAAAAAEACr2kwL81V6YgEAAQDzVXpi",
        // Set the user ID.
        uid: 422,
      },
      client: AgoraRTC.createClient({ mode: "rtc", codec: "vp8" }),
      localTracks: {
        videoTrack: null,
        audioTrack: null
      },
      remoteTracks: {
        videoTrack: null,
        audioTrack: null
      },
      remoteUsers: {
        id: null
      },
    }
  },
  created() {
    // this.startBasicCall()
  },
  mounted() {
    this.client.on("user-published", this.handleUserPublished);
    this.client.on("user-unpublished", this.handleUserUnpublished);
    this.client.on("user-left", this.handleRemoteLeft);
    this.client.on("user-joined", function () {
      console.log('userjoin');
    });
    this.client.on('connection-state-change', this.handleStateChangelLeft)
    // AgoraRTC.onMicrophoneChanged = async (changedDevice) => {
    //   console.log(11);
    //   // When plugging in a device, switch to a device that is newly plugged in.
    //   if (changedDevice.state === "ACTIVE") {
    //     this.localTracks.audioTrack.setDevice(changedDevice.device.deviceId);
    //     // Switch to an existing device when the current device is unplugged.
    //   } else if (changedDevice.device.label === this.localTracks.audioTrack.getTrackLabel()) {
    //     const oldMicrophones = await AgoraRTC.getMicrophones();
    //     oldMicrophones[0] && this.localTracks.audioTrack.setDevice(oldMicrophones[0].deviceId);
    //   }
    // }

    // AgoraRTC.onCameraChanged = async (changedDevice) => {
    //   console.log(22);
    //   // When plugging in a device, switch to a device that is newly plugged in.
    //   if (changedDevice.state === "ACTIVE") {
    //     this.localTracks.videoTrack.setDevice(changedDevice.device.deviceId);
    //     // Switch to an existing device when the current device is unplugged.
    //   } else if (changedDevice.device.label === this.localTracks.videoTrack.getTrackLabel()) {
    //     const oldCameras = await AgoraRTC.getCameras();
    //     oldCameras[0] && this.localTracks.videoTrack.setDevice(oldCameras[0].deviceId);
    //   }
    // }
  },
  updated() {
    // this.startBasicCall()
  },
  methods: {
    handleRemoteLeft: function (user, mediaType) {
      // this.subscribe(user, mediaType);
      console.log('对方离开了');
    },
    handleStateChangelLeft: function (user, mediaType) {
      // this.subscribe(user, mediaType);
      console.log('状态改变了');
    },
    handleUserPublished: function (user, mediaType) {
      console.log('开启发布监听');
      this.remoteUsers.id = user.uid;
      this.subscribe(user, mediaType);
    },
    handleUserUnpublished: async function (user, mediaType) {
      console.log('监听unpublish');
      if (mediaType === 'video') {
        const id = user.uid;
        delete this.remoteUsers[id];
        this.$refs.remotevideoRef.remove();
      }
    },
    // subscribr remote
    subscribe: async function (user, mediaType) {
      console.log('开启订阅');
      console.log(user);
      const uid = user.uid;
      await this.client.subscribe(user, mediaType);
      console.log("subscribe success");
      if (mediaType === 'video') {
        this.remoteTracks.videoTrack = user.videoTrack
        this.remoteTracks.videoTrack.play(this.$refs.remotevideoRef);
      }
      if (mediaType === 'audio') {
        user.audioTrack.play();
      }
    },
    leave: async function () {
      console.log('点击离开');
      for (var trackName in this.localTracks) {
        var track = this.localTracks[trackName];
        if (track) {
          track.stop();
          track.close();
          this.localTracks[trackName] = undefined;
        }
      }
      // Remove remote users and player views.
      this.remoteUsers = {};
      // leave the channel

      this.$refs.remotevideoRef = null
      this.$refs.localvideoRef = null
      this.client.unpublish();
      await this.client.leave();
      console.log('leave了');

    },
    join: async function () {
      this.client.on("user-left", (user, mediaType) => {
        console.log('有人离开了');
      });
      this.client.on("user-joined", function (user) {
        console.log(user);
      });
      // Add an event listener to play remote tracks when remote user publishes.
      this.client.on("user-published", this.handleUserPublished);
      this.client.on("user-unpublished", this.handleUserUnpublished);
      
      

      // Join a channel and create local tracks. Best practice is to use Promise.all and run them concurrently.
      [this.options.uid, this.localTracks.audioTrack, this.localTracks.videoTrack] = await Promise.all([
        // Join the channel.
        this.client.join(this.options.appid, this.options.channel, this.options.token || null, this.options.uid || null),
        // Create tracks to the local microphone and camera.
        AgoraRTC.createMicrophoneAudioTrack(),
        AgoraRTC.createCameraVideoTrack()
      ]);

      // Play the local video track to the local browser and update the UI with the user ID.
      this.localTracks.videoTrack.play(this.$refs.localvideoRef);

      // Publish the local video and audio tracks to the channel.
      await this.client.publish(Object.values(this.localTracks));
      console.log("publish success");
      
    }
  }
}
</script>

<style scope>
.con {
  display: flex;
  margin: 80px auto;
}

.remoteVideo {
  width: 400px;
  height: 300px;
  border: 3px solid red;
}

.localVideo {
  width: 400px;
  height: 300px;
  border: 3px solid blue;
}
</style>